package com.jwt.Handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jwt.pojo.ResponseResult;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
@Component
public class JwtLoginFailureHandler extends SimpleUrlAuthenticationFailureHandler {
	@Resource
	ObjectMapper objectMapper;

	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
		response.setContentType("application/json;charset=utf-8");
		String errorMsg="";
		if (exception instanceof UsernameNotFoundException) {
			errorMsg="用户名不存在";
		}else if (exception instanceof LockedException){
			errorMsg="户被冻结";
		} else if (exception instanceof BadCredentialsException) {
			errorMsg="用户名或密码错误";
		}else {
			errorMsg=exception.getMessage();
		}
		ResponseResult<?> result=new ResponseResult<>();
		result.setCode(2);
		result.setFlag(false);
		result.setMsg(errorMsg);
		String s = objectMapper.writeValueAsString(result);
		response.getWriter().write(s);
	}
}
